<?php
/**
 * Контроллер для SEO
 *
 * @author kingop
 */
class SeoController extends CustomControllerAction {
    
    public $configObj = null;
    
    public function preDispatch() {
        parent::preDispatch();

        $this->configObj = DatabaseObject_SeoConfig::GetConfigObject($this->db);
    }
    
    public function updateConfig($name, $value) {
        return DatabaseObject_SeoConfig::UpdateConfigValue($this->db, $name, $value);
    }
    
    public function indexAction() {
        $this->view->page_title = 'Панель оптимизатора';
    }
    
    public function metatendersAction() {
        $this->view->page_title = 'Управление мета-тегами тендеров';

          if ($this->getRequest()->isPost()) {
            
            $_SESSION['filter_cat'] = $this->getRequest()->getPost('cats_filter');
            $_SESSION['filter_project'] = $this->getRequest()->getPost('projects_filter');
            $_SESSION['filter_archive'] = $this->getRequest()->getPost('archive_filter');
            $_SESSION['search'] = $this->getRequest()->getPost('search');
        }elseif (!$this->getRequest()->getParam('p')){
            $_SESSION['filter_cat'] = array();
            $_SESSION['filter_project'] = array();
            $_SESSION['filter_archive'] = '2';
            $_SESSION['search'] = '';
        }
        
        if (($_GET['sort']) && ($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['tender_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['tender_sort'])) {
            $temp = explode(' ', $_SESSION['tender_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'name';
            $order = 'asc';
            $_SESSION['tender_sort'] = $sort . ' ' . $order;
        }
        $options = array('order' => 'p.' . $sort . ' ' . $order);
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['tenders_per_page_admin'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Tender::GetFilterCount($this->db, array('idCat' => $_SESSION['filter_cat'], 'idProject' => $_SESSION['filter_project'], 'archive' => $_SESSION['filter_archive'], 'search' => $_SESSION['search']), array('order' => $_SESSION['tender_sort'])) / $limit);
        $tender = DatabaseObject_Tender::FilterTenders($this->db, array('idCat' => $_SESSION['filter_cat'], 'idProject' => $_SESSION['filter_project'], 'archive' => $_SESSION['filter_archive'],'search' => $_SESSION['search']), array('order' => $_SESSION['tender_sort'], 'limit' => $limit, 'offset' => $offset));

        $cats = DatabaseObject_Categories::GetCategories($this->db);
        $project = DatabaseObject_Project::GetProjects($this->db);
        $this->view->cats_filter = $_SESSION['filter_cat'];
        $this->view->projects_filter = $_SESSION['filter_project'];
        $this->view->archive_filter = $_SESSION['filter_archive'];
        $this->view->tenders = $tender;
        $this->view->cats = $cats;
        $this->view->projects = $project;
        $this->view->option_sort = $option_sort;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->pages = $pages;
        $this->view->page = $page;
    }
    
    public function edittenderAction() {
        $this->view->page_title = 'Редактирование мета-тегов тендера';
        
        $id = $this->getRequest()->getParam('id');
        $tender = new DatabaseObject_Tender($this->db);
        $tender->load($id);
        
        if($this->getRequest()->isPost()) {
            $tender->title = $this->getRequest()->getPost('title');
            $tender->keywords = $this->getRequest()->getPost('keywords');
            $tender->description = $this->getRequest()->getPost('description');
            $tender->save();
            
            $message = sprintf('Изменены мета-теги тендера "%s" оптимизатором "%s"', $tender->name, Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
            
            $this->_redirect($this->getCustomUrl(array(), 'seoedittendercomplete'));
        }
        
        $this->view->tender = $tender;
    }
    
    public function edittendercompleteAction() {
        $this->view->page_title = 'Успешно';
    }
    
    public function configAction() {
        $this->view->page_title = "Настройки";
        if ($this->getRequest()->isPost()) {
            $configs = array_keys($this->seo_config);
            foreach ($configs as $key) {
                $this->updateConfig($key, $this->getRequest()->getPost($key));
            }

            $message = sprintf('SEO-настройки сайта были изменены оптимизатором "%s"', Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
            
            $this->_redirect($this->getUrl('configcomplete'));
        }

        $this->view->configObj = $this->configObj;
    }
    
    public function configcompleteAction() {
        $this->view->page_title = 'Успешно';
        
        /*$this->view->page_title = "Настройки";
        if ($this->getRequest()->isPost()) {
            $configs = array_keys($this->configuration);
            foreach ($configs as $key) {
                $this->updateConfig($key, $this->getRequest()->getPost($key));
            }

            $message = sprintf('SEO-настройки сайта были изменены оптимизатором "%s"', Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
            
            $this->_redirect($this->getUrl('configcomplete'));
        }

        $this->view->configObj = $this->configObj;*/
    }
    
    public function pagesAction() {
        $this->view->page_title = 'Управление страницами';
        $p_page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['pages_per_page'];
        $offset = ($p_page - 1) * $limit;
        $p_pages = ceil(DatabaseObject_Pages::GetCount($this->db) / $limit);
        
        $pages = DatabaseObject_Pages::GetPages($this->db, array('limit' => $limit, 'offset' => $offset));
        
        $this->view->p_page = $p_page;
        $this->view->p_pages = $p_pages;
        $this->view->pages = $pages;
    }
    
    public function addpageAction() {
        $this->view->page_title = "Добавление страницы";
        $request = $this->getRequest();
        $fp = new FormProcessor_PageAdd($this->db);


        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                
                $message = sprintf('Добавлена страница "%s" оптимизатором "%s"', $fp->page->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'seoaddpagecomplete'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }


        $this->view->fp = $fp;
    }
    
    public function addpagecompleteAction() {
        $this->view->page_title = 'Успешно';
    }
    
    public function deletepagesAction() {
        $id = $this->getRequest()->getParam('id');
        $page = new DatabaseObject_Pages($this->db);
        if (!$page->load($id)) {
            echo 'Страница не найдена';
            exit;
        }
        if (!$page->delete()) {
            echo 'Ошибка удаления страницы';
            exit;
        }
        
        $message = sprintf('Страница "%s" была удалена оптимизатором "%s"', $page->name, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
        
        echo 'ok';
        exit;
    }
    
    public function editpageAction() {
        $this->view->page_title = 'Редактирование страницы';
        
        $id = $this->getRequest()->getParam('id');
        
        $page = new DatabaseObject_Pages($this->db);
        $page->load($id);
        $fp = new FormProcessor_PageEdit($this->db, $id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                
                $message = sprintf('Страница "%s" была отредактирована оптимизатором "%s"', $fp->page->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'seoeditpagecomplete'));
            }
        }

        $this->view->fp = $fp;
    }
    
    public function editpagecompleteAction() {
        $this->view->page_title = 'Успешно';
    }
}

?>